﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SYS.Common.Broker;
using IBatisNet.Extend;
using IBatisNet.Common.Utilities;
using System.Data;

namespace ExpertMIS.Admin.UserControl
{
    public delegate void OnDeleteDelegate(string OID);
    public delegate void OnEditDelegate(string OID);
    public delegate void OnCheckedValueChangedDelegate(string OID, bool isChecked);

    public partial class PagingGridView : System.Web.UI.UserControl
    {
        #region Fields                
        private static int _pagingSize = int.Parse(ExpertMIS.Codes.Utility.GetEnvironmentValue("PageSize"));
        #endregion

        #region Declare Delegations

        public event OnDeleteDelegate OnDelete;
        public event OnEditDelegate OnEdit;

        #endregion

        #region Public Field

        public string EditClientURL;
        public string DeleteClientScript;
        public string PK;
        public string DeleteClientURL;

        #endregion

        #region Properties

        protected int Total
        {
            get
            {
                if (!string.IsNullOrEmpty(hfTotal.Value))
                {
                    int tmp = 0;
                    if (int.TryParse(hfTotal.Value, out tmp))
                    {
                        return tmp;
                    }
                    else
                    {
                        return Start = 1;
                    }
                }
                else
                    return Start = 1;
            }
            set
            {
                hfTotal.Value = value.ToString();
            }
        }

        protected int Start
        {
            get
            {
                if (!string.IsNullOrEmpty(hfStart.Value))
                {
                    int tmp = 0;
                    if (int.TryParse(hfStart.Value, out tmp))
                    {
                        return tmp;
                    }
                    else
                    {
                        return Start = 1;
                    }
                }
                else
                    return Start = 1;
            }
            set
            {
                hfStart.Value = value.ToString();
            }
        }

        public string GetStartHiddenFieldClientID()
        {
            return hfStart.ClientID;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(PK)) PK = "F_OID";
            if (string.IsNullOrEmpty(EditClientURL)) EditClientURL = "{0}";
            if (string.IsNullOrEmpty(DeleteClientScript)) DeleteClientScript = "{0}";
            if (string.IsNullOrEmpty(DeleteClientURL)) DeleteClientURL = "{0}";
        }

        protected override void Render(HtmlTextWriter writer)
        {
            QueryResult(); // 在此处调用，其它地方不再需要调用的语句，否则将重复查询

            SetTemplateColumnDisplay(TmpColVisible);

            base.Render(writer);
        }

        private void QueryResult()
        {
            string searchKey = string.Empty;

            if (Request["search"] != null)
            {
                // wdong, 2009-9-5,去除searchkey内容前后的"{", "}",
                // 使用"{"和"}"是因为获取get参数search的值
                // 例如：xxx.com?search={a=b AND c=d},不加{}则变为search=a=b AND c=d...
                string str = HttpUtility.UrlDecode(Request["search"]);
                if (str.IndexOf('{') > -1)
                {
                    str = str.Replace("{", "");
                }

                if (str.IndexOf('}') > -1)
                {
                    str = str.Replace("}", "");
                }

                searchKey = str;
            }

            // 动态增加绑定列，且将模版列放后
            IList<BoundField> cols = new List<BoundField>();
            ObjectManagerBroker mngrBroker = ObjectManagerBroker.GetObjectManagerBroker();
            IList<ObjectDetails> details = mngrBroker.GetObjectDetailsByName(ObjectName);
            foreach (ObjectDetails detail in details)
            {
                if (detail.Visible)
                {
                    BoundField col = new BoundField();
                    if (detail.HasCode)
                    {
                        col.DataField = detail.CodeAliasName;
                    }
                    else
                    {
                        col.DataField = detail.FieldName;
                    }
                    col.HeaderText = detail.DispName;

                    cols.Add(col);
                }
            }

            int nCount = cols.Count;
            while(nCount > 0)
            {
                DataControlField col = cols[nCount - 1] as DataControlField;
                col.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
                col.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
                gvList.Columns.Insert(0, cols[nCount - 1]);

                nCount = nCount - 1;
            }

            ObjectBroker brokerInfo = ObjectManagerBroker.GetObjectManagerBroker().GetObjectBrokerByObjectName(ObjectName);
            BaseBroker broker = null;
            if (brokerInfo != null) // 外连了一个Broker对象
            {
                broker = brokerInfo.CreateInstance() as BaseBroker;
            }

            PagingSize pagingSize = new PagingSize();

            pagingSize.Limit = _pagingSize;
            pagingSize.Start = Start;
            pagingSize.SearchKey = broker != null ? broker.ProcessQueryCondition(QueryExpression.CreateQueryExpression(searchKey)) : searchKey;
            pagingSize.SortExpression = string.IsNullOrEmpty(gvList.SortExpression) ? PK + "  DESC" : gvList.SortExpression;
            gvList.DataSource = SQLBuilderBroker.GetSQLBuilderBroker().GetObjectView(ObjectName, pagingSize);

            Total = pagingSize.Total;
            lbCurPageCount.Text =Total==0?"0":Start.ToString();
            lbTotalPageCount.Text =((int)System.Math.Ceiling((double)Total / _pagingSize)).ToString();
            gvList.AutoGenerateColumns = false;
            gvList.DataBind();
        }

        protected void gvList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 设置模板列的可见属性
        /// </summary>
        public void SetTemplateColumnDisplay(bool visible)
        {
            gvList.Columns[0].Visible = visible;
        }

        public bool TmpColVisible
        {
            get 
            {
                if (ViewState["_TmpColVisible_"] == null)
                { 
                    return true; 
                } 
                else
                { 
                    return (bool)ViewState["_TmpColVisible_"]; 
                }
            }
            set
            {
                ViewState["_TmpColVisible_"] = value;
            }
        }

        public string ObjectName
        {
            get
            {
                return ViewState["_OBJECTNAME_"] as string;
            }
            set
            {
                ViewState["_OBJECTNAME_"] = value;
            }
        }

        public string FilterString
        {
            get
            {
                return ViewState["_FILTERSTRING_"] as string;
            }
            set
            {
                ViewState["_FILTERSTRING_"] = value;
            }
        }

        protected void gvList_Sorted(object sender, EventArgs e)
        {

        }

        public GridView GetGridView()
        {
            return gvList;
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (gvList.SelectedIndex != -1)
            {
                if ("delete".Equals(e.CommandName))
                {
                    if (OnDelete != null)
                    {
                        DataRow row = (gvList.SelectedRow.DataItem as DataRow);
                        OnDelete(row[PK] as string);
                    }
                }
                else if ("edit".Equals(e.CommandName))
                {
                    if (OnEdit != null)
                    {
                        DataRow row = (gvList.SelectedRow.DataItem as DataRow);
                        OnEdit(row[PK] as string);
                    }
                }
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView row = e.Row.DataItem as DataRowView;
                ImageButton ibEdit = e.Row.FindControl("ibEdit") as ImageButton;
                ibEdit.PostBackUrl = string.Format(EditClientURL, row[PK]);

                ImageButton ibDelete = e.Row.FindControl("ibDelete") as ImageButton;
                ibDelete.OnClientClick = string.Format(DeleteClientScript, row[PK]);
                ibDelete.PostBackUrl = string.Format(DeleteClientURL, row[PK]);

                LinkButton lbEdit = e.Row.FindControl("lbEdit") as LinkButton;
                lbEdit.PostBackUrl = string.Format(EditClientURL, row[PK]);

                LinkButton lbDelete = e.Row.FindControl("lbDelete") as LinkButton;
                lbDelete.PostBackUrl = string.Format(DeleteClientURL, row[PK]);
                lbDelete.OnClientClick = string.Format(DeleteClientScript, row[PK]);

                // 显示文字或者图片，放在系统环境变量中
                string visible = ExpertMIS.Codes.Utility.GetEnvironmentValue("IsDisplayImageInGridView");
                if ("true".Equals(visible))
                {
                    ibEdit.Visible = true;
                    ibDelete.Visible = true;

                    lbEdit.Visible = false;
                    lbDelete.Visible = false;
                }
                else
                {
                    ibEdit.Visible = false;
                    ibDelete.Visible = false;

                    lbEdit.Visible = true;
                    lbDelete.Visible = true;
                }
            }
        }

        protected void lbPrior_Click(object sender, EventArgs e)
        {
            if (Start - 1 > 0)
            {
                Start--;
            }
        }

        protected void lbNext_Click(object sender, EventArgs e)
        {
            if (Start + 1 <= (int)System.Math.Ceiling((double)Total / _pagingSize))
            {
                Start++;
            }
        }
    }
}